package com.example.security.handle;

import com.example.security.bean.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/5/29 20:02
 * @version: 0.1
 * @Description :
 * @Modified By:
 */
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {


    private SpringSessionBackedSessionRegistry sessionRegistry;


    public MyLogoutSuccessHandler(SpringSessionBackedSessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request,HttpServletResponse res,Authentication authentication) throws IOException, ServletException {
        res.setContentType("application/json;charset=utf-8");
        if (authentication != null) {
            UserInfo userInfo = (UserInfo) authentication.getPrincipal();
            List<SessionInformation> informations = sessionRegistry.getAllSessions(userInfo,false);
            informations.forEach(SessionInformation::expireNow);
            PrintWriter out = res.getWriter();
            Map<String, Object> map = new HashMap<>();
            map.put("status",200);
            map.put("msg","注销登录成功!");
            out.write(new ObjectMapper().writeValueAsString(map));
            out.flush();
            out.close();
        }
    }
}
